<?php

App::uses('AdminController', 'Controller');

class AdminHomeController extends AdminController {
    
    public $uses = array('HomeItem');
    
    public function index() {
        $this->set('homeItems', $this->HomeItem->find('all'));
    }
    
    public function save_positions() {
        $this->autoRender = false;
        
        if ($this->HomeItem->saveAll($this->data)) {
            $message = 'Redosled je uspešno sačuvan.';
        } else {
            header('HTTP/1.0 404 Error');
            $message = 'Greška pri čuvanju podataka.';
        }
        
        die($message);
    }
    
    public function create() {
        $this->set('data', $this->HomeItem->create());
        $this->render('form');
    }
    
    public function edit($id) {
        $this->set('data', $this->HomeItem->findById($id));
        $this->render('form');
    }
    public function save() {
        $data = $this->data;
        
        if (! empty($data)) {
            $noImage = (int)$data['HomeItem']['no-image'];
            
            $file = $data['HomeItem']['image_file'];
            
            if (! $file['error']) {
                $data['HomeItem']['image'] = $file['name'];
            }
            if ($noImage) {
                $data['HomeItem']['image'] = '';
            }
            
            $this->HomeItem->create($data);
            
            $prev = array();
            if ($this->HomeItem->id) {
                $prev = $this->HomeItem->findById($this->HomeItem->id);
            }
            
            if (! $this->HomeItem->validates()) {
                $this->setFlash('Uneti podaci nisu validni.');
                $this->set('data', $data);
                return $this->render('form');
            }
            
            if (! $this->HomeItem->save($data)) {
                $this->setFlash('Greška pri čuvanju podataka.');
                $this->set('data', $data);
                return $this->render('form');
            }
            
            // delete old image
            $oldImage = Set::extract('HomeItem.image', $prev);
            $newImage = $data['HomeItem']['image'];
            if ($oldImage != $newImage && !empty($oldImage)) {
                debug(remove_file('img' . DS . 'home_items' . DS . $oldImage));
            }
            
            if (! $file['error'] && !$noImage) {
                $from = $file['tmp_name'];
                $to   = 'img' . DS . 'home_items' . DS . $file['name'];
                upload_file($from, $to);
            }
            
            $this->setFlash('Sačuvano.', 'ok');
            $this->redirect('edit/'.$this->HomeItem->id);
        }
        $this->redirect('index');
    }

    public function remove($id) {
        if ($this->HomeItem->delete($id)) {
            $this->setFlash('Stavka je obrisana.', 'ok');
        } else {
            $this->setFlash('Greška pri brisanju.');
        }
        $this->redirect('index');
    }
    
}
